/* 必须放在文件最上方才能替换吗? */
/* #include <pthreadalt.h> */
// #include <dinfra/init_fin.h>
#include <pthread.h>
static void sys_init(void);
MAY_UNUSED static void sys_fin(void);
static void cflow_init(void);
MAY_UNUSED static void cflow_fin(void);

/* 通过包含这个文件定义系统初始化/终止，线程初始化/终止流程 */
static pthread_key_t thread_init_key;


static void thread_destructor(void *_){
	(void) _;
	cflow_fin();
}
static void proc_initializer(){
	sys_init();
	
	pthread_key_create(&thread_init_key, thread_destructor);
}

static void reg_thread_destructor(){
	pthread_setspecific(thread_init_key, (void *)-1);
}

static void __thread_initializer(){
	cflow_init();
	reg_thread_destructor();
}

#ifndef METALC_DYNLIB
static int swi = 0;
__attribute__((destructor)) void __pthreadalt_proc_destructor(){
	if (swi){
		// fprintf(stderr, "proc destructor, execute initializer times %d\n", swi);
		cflow_fin();
		sys_fin();
		swi = 0;
	}
}
void thread_initializer(){
	__thread_initializer();
}
__attribute__((constructor)) void __pthreadalt_init_contructor() { 
	if (!swi){
		// fprintf(stderr, "thread constructor \n");
		proc_initializer(); 
		/*fprintf(stderr, "start thread_initializer \n");*/ 
		thread_initializer();
	}
	swi++;
}
#endif